import axios from 'axios';
import { config } from '../config';

interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
}

interface OCRResponse {
  text: string;
}

const api = axios.create({
  baseURL: config.api.baseURL,
  timeout: config.api.timeout,
  headers: {
    'Content-Type': 'multipart/form-data',
  },
});

// 响应拦截器
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 413) {
      error.message = '文件太大，请选择小于10MB的文件';
    }
    return Promise.reject(error);
  }
);

export const pdfApi = {
  async performOCR(file: File, lang: string = 'chi_sim+eng'): Promise<string> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('lang', lang);
    
    const response = await api.post<ApiResponse<OCRResponse>>('/pdf/ocr', formData);
    return response.data.data.text;
  },

  async convertToWord(file: File): Promise<Blob> {
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await api.post<Blob>('/pdf/to-word', formData, {
      responseType: 'blob'
    });
    return new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
  },

  async convertToPPT(file: File): Promise<Blob> {
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await api.post<Blob>('/pdf/to-ppt', formData, {
      responseType: 'blob'
    });
    return new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
  },

  async mergePDFs(files: File[]): Promise<Blob> {
    const formData = new FormData();
    files.forEach(file => {
      formData.append('files', file);
    });
    
    const response = await api.post<Blob>('/pdf/merge', formData, {
      responseType: 'blob'
    });
    return new Blob([response.data], { type: 'application/pdf' });
  },

  async splitPDF(file: File, pageRanges: string): Promise<Blob> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('page_ranges', pageRanges);
    
    const response = await api.post<Blob>('/pdf/split', formData, {
      responseType: 'blob'
    });
    return new Blob([response.data], { type: 'application/pdf' });
  }
}; 